<template>
	<view class="cart-container">
		<view class="cart-good-area" v-for="(item, index) in cartGoodList" :key="item.goodsid">
			<shop-good :goodsname="item.goodsname" :goodsprice="item.price * item.goodsnum" :goodsimg="item.goodsimg" :checkState="item.checked" :gid="item.goodsid" :mid="item.merchantsid">
				<template v-slot:radio>
					<label class="radio">
						<radio :checked="item.checked" @click="editGoodChosenStatus(item, index)"/><text></text>
					</label>
				</template>
				<template v-slot:choice>
					<van-cell :title="item.choicename" title-width="300rpx" is-link arrow-direction="down" @click="openCurrentGoodPopup(item)"/>
				</template>
				<template v-slot:stepper>
					<van-stepper :value="item.goodsnum" :input-width="20" :button-size="16" max="5" @change="numChange(item, index, $event)"/>
				</template>
			</shop-good>
		</view>
		<!-- 底部购物车结算区域 -->
		<view class="bottom-compute-area">
			<label class="radio">
				<radio :disabled="cartGoodList.length === 0" :checked="cartBottomComputedObj.checkAllState" @click="checkAllChange" /><text>全选</text>
			</label>
			<text class="goods-price">合计:&yen;{{ cartBottomComputedObj.totalPrice.toFixed(2) }}</text>
			<text class="del-chosen" @click="delChosen">删除选中</text>
			<van-button type="danger" @click="gotoOrderPage">去结算:{{ cartBottomComputedObj.totalNum }}</van-button>
		</view>
		<!-- 商品属性选项值区域 -->
		<van-popup
		  :show="isShow"
			position="bottom"
			custom-style="height: 80%;padding: 30rpx"
			@close="editCLose"
			closeable round>
			<view class="popup-top-area">
				<image :src="currentChosenGoodImg" mode=""></image>
				<view>
					<text v-if="currentChosenChoiceIdIven[0]" class="goods-price">&yen; {{ cartGoodList[currentChosenIndex].price.toFixed(2) }}</text><text v-else>无货</text>
					<van-cell :label="cartGoodList[currentChosenIndex].choicename" title="已选商品分类" center />
				</view>
			</view>
			<van-radio-group v-for="(item, index) in currenGoodAttrAndChoice" :key="item.attrid" :value="currentChosenChoiceId[index]" @change="choiceChange(index, $event)">
				<text>{{ item.attrname }}</text>
				<block v-for="val in item.children" :key="val.choiceid">
					<van-radio :name="val.choiceid + ''">{{ val.choicename }}</van-radio>
				</block>
			</van-radio-group>
			<view class="btn-area">
				<button type="primary"
				:disabled="!currentChosenChoiceIdIven[0]"
				@click="commitCurrentCartInfo(currentChosenGoodId, currentChosenChoiceId.join(','), cartGoodList[currentChosenIndex].price, cartGoodList[currentChosenIndex].goodsnum, cartGoodList[currentChosenIndex].checked)"
				>
					确定
				</button>
			</view>
		</van-popup>
		<shop-empty :show="cartGoodList.length === 0"></shop-empty>
	</view>
</template>

<script>
	export default {
		onLoad() {
			this.getUserCartInfo()
		},
		onShow() {
			this.getUserCartInfo()
		},
		onPullDownRefresh() {
			this.getUserCartInfo()
		},
		data() {
			return {
				// 存储该用户购物车中的商品列表
				cartGoodList: [],
				// 被选中的商品列表
				checkedGoodsList: [],
				// 底部信息对象
				cartBottomComputedObj: {
					// 全选按钮单选框状态
					checkAllState: false,
					// 被选中商品的总价格
					totalPrice: 0,
					// 被选中商品的总数量
					totalNum: 0
				},
				// popup弹出层是否可见的变量
				isShow: false,
				// 当前弹出popup弹出层商品的商品id
				currentChosenGoodId: 0,
				// 当前弹出popup弹出层的商品的属性以及属性选项值
				currenGoodAttrAndChoice: [],
				// 当前商品选中的属性选项值id
				currentChosenChoiceId: [],
				// 当前商品指定属性选项值商品id的库存信息
				currentChosenChoiceIdIven: [],
				// 当前选中商品的图片信息
				currentChosenGoodImg: '',
				// 当前商品指定属性选项值的基础价格
				currentGoodBasePrice: 0,
				// 被激活商品属性选项值的信息
				activeChoiceInfo: [],
				// 当前选中商品的下标值默认为-1
				currentChosenIndex: -1
			}
		},
		methods: {
			// 获取用户购物车信息
			async getUserCartInfo() {
				if(!uni.getStorageSync('uid')) {
					this.cartGoodList = []
					this.checkedGoodsList = []
					this.cartBottomComputedObj = {
					// 全选按钮单选框状态
					checkAllState: false,
					// 被选中商品的总价格
					totalPrice: 0,
					// 被选中商品的总数量
					totalNum: 0
					}
					return uni.showModal({
						title: '提示',
						content: '您还未登录，是否前往登录',
						cancelText: '取消',
						confirmText: '确定',
						success(res) {
							if(res.confirm) { uni.navigateTo({
								url: '/subpages/userlogin/userlogin'
							}) } else if(res.cancel) {
								console.log('取消按钮')
							}
						}
					})
				}
				const { data: res } = await uni.$http.get('/cart', { id: uni.getStorageSync('uid') })
				if(res.meta.status !== 200) return uni.showToast({
					title: res.meta.message,
					icon: 'error',
					duration: 1500
				})
				this.cartGoodList = res.recordset
				console.log(this.cartGoodList)
				this.getCheckGoodsInfo()
			},
			// 获取该类商品的其他属性选项值
			async getGoodOtherAttrChoice(goodsid) {
				this.currenGoodAttrAndChoice = []
				const { data: res } = await uni.$http.get('/goods/detail', { id: goodsid })
				if(res.meta.status !== 200) return uni.showToast({
					title: '选项值信息失败',
					icon: 'error',
					duration: 1000
				})
				for(let item of res.recordsets[2]) {
					// 如果attrAndChoice中没有此节点，需要加入新的对象包含这个商品属性
					if(!this.currenGoodAttrAndChoice.find(val => val.attrid === item.attrid)) {
						this.currenGoodAttrAndChoice.push({
							attrid: item.attrid,
							attrname: item.attrname,
							children: [{
								choiceid: item.choiceid,
								choicename: item.choicename,
								choiceprice: item.choiceprice
							}]
						})
					} else {
						// 如果attrAndChoice中已经有该商品的属性id 直接加入此id的children节点中
						const index = this.currenGoodAttrAndChoice.findIndex(val => val.attrid === item.attrid)
						this.currenGoodAttrAndChoice[index].children.push({
							choiceid: item.choiceid,
							choicename: item.choicename,
							choiceprice: item.choiceprice
						})
					}
				}
			},
			// 获取被选中商品指定属性选项值id的库存信息
			async getGoodChoiceInven(gid, cid) {
				const { data: res } = await uni.$http.get('/goods/inven', { gid: gid, cid: cid })
				if(res.meta.status !== 200) return uni.showToast({
					title: res.meta.message,
					icon: 'error',
					duration: 1500
				})
				this.$set(this.currentChosenChoiceIdIven, 0, res.recordset[0])
			},
			// 根据属性选项值id获取属性选项值信息
			async getActiveChoiceInfo() {
				const { data: res } = await uni.$http.get('/attr/choice', { id: this.currentChosenChoiceId.join(',') })
				if(res.meta.status !== 200) return uni.showToast({
					title: res.meta.message,
					icon: 'error',
					duration: 1500
				})
				this.activeChoiceInfo = res.recordset
				// 获取属性选项值id为异步任务
				this.currentChosenIndex = this.cartGoodList.findIndex(item => item.goodsid === this.currentChosenGoodId)
				this.getNewPrice()
			},
			// 提交当前修改的商品信息至该用户的后台购物车
			async commitCurrentCartInfo(gid, id, price, num, checkstatus) {
				const { data: res } = await uni.$http.put('/cart/modify', { uid: uni.getStorageSync('uid'), gid, id, price, num, checkstatus })
				if(res.meta.status !== 200) return uni.showToast({
					title: res.meta.message,
					icon: 'error',
					duration: 1500
				})
				this.isShow = false
				// 修改购物车商品信息成功 重新加载页面
				this.getUserCartInfo()
				this.editCLose()
			},
			// 去结算按钮被点击后触发  跳转至生成订单界面
			gotoOrderPage() {
				console.log('ok')
				if(this.checkedGoodsList.length === 0) return uni.showToast({
					title: '请选择商品',
					icon: 'error',
					duration: 1500
				})
				uni.navigateTo({
					url: '/subpages/ordersgenerate/ordersgenerate?type=1'
				})
			},
			// 购物车全选按钮被点击时触发
			async checkAllChange() {
				const { data: res } = await uni.$http.put('/cart/modify', { uid: uni.getStorageSync('uid'), status: !this.cartBottomComputedObj.checkAllState })
				if(res.meta.status !== 200) return uni.showToast({
					title: res.meta.message,
					icon: 'error',
					duration: 1000
				})
				this.cartBottomComputedObj.checkAllState = !this.cartBottomComputedObj.checkAllState
				this.cartGoodList.forEach(item => {
					item.checked = this.cartBottomComputedObj.checkAllState
				})
				this.getCheckGoodsInfo()	
			},
			// 筛查用户已勾选的商品信息
			getCheckGoodsInfo() {
				this.cartBottomComputedObj.totalPrice = 0
				this.cartBottomComputedObj.totalNum = 0
				this.checkedGoodsList = this.cartGoodList.filter(item => item.checked)
				this.cartBottomComputedObj.checkAllState = this.checkedGoodsList.length === this.cartGoodList.length
				this.checkedGoodsList.forEach(item => {
					this.cartBottomComputedObj.totalPrice += item.price * item.goodsnum
					this.cartBottomComputedObj.totalNum += item.goodsnum
				})
			},
			// 当购物车中的cell单元格被点击时打开popup弹出层
			openCurrentGoodPopup(item) {
				this.isShow = true
				// 当前购物车选中商品的商品id
				this.currentChosenGoodId = item.goodsid,
				// 当前选中商品的默认属性选项值id便于渲染在popup弹出层的单选按钮上
				this.currentChosenChoiceId = item.choiceid.split(',')
				// 当前购物车选中商品的商品图片
				this.currentChosenGoodImg = item.goodsimg
				// 当前选中商品的基本价格
				this.currentGoodBasePrice = item.goodsbaseprice
				// 获取当前商品的属性及属性选项值信息
				this.getGoodOtherAttrChoice(item.goodsid)
				// 获取当前商品默认激活的属性选项值的信息
				this.getActiveChoiceInfo()
				// 获取当前商品属性选项值的库存信息
				this.getGoodChoiceInven(this.currentChosenGoodId, this.currenGoodAttrAndChoice.join(','))
			},
			// 当购物车popup弹出层商品属性修改后触发
			choiceChange(index, e) {
				this.currentChosenChoiceId[index] = e.detail
				this.$set(this.currentChosenChoiceId, index, e.detail)
				this.getActiveChoiceInfo()
				this.getGoodChoiceInven(this.currentChosenGoodId, this.currentChosenChoiceId.join(','))
			},
			// 购物车商品属性修改popup弹出层关闭时触发
			editCLose() {
				this.isShow = false
				// 当popup弹出层关闭后 清空所有当前存储选中商品信息的变量
				this.currenGoodAttrAndChoice = []
				this.currentChosenChoiceId = []
				this.currentChosenChoiceIdIven = []
				this.currentChosenGoodId = 0
				this.activeChoiceInfo = []
				this.currentChosenIndex = -1
			},
			// 根据用户选区的属性选项值id 确定商品价格
			getNewPrice() {
				let sum = 0
				this.activeChoiceInfo.forEach(item => {
					sum += item.choiceprice
				})
				this.cartGoodList[this.currentChosenIndex].price = this.currentGoodBasePrice + sum
			},
			// 商品数目发生变化时触发
			numChange(item, i, e) {
				this.cartGoodList[i].goodsnum = e.detail
				this.commitCurrentCartInfo(item.goodsid, item.choiceid, item.price, item.goodsnum, item.checked)
				this.getCheckGoodsInfo()
			},
			// 单个商品选中状态发生变化时触发
			editGoodChosenStatus(item, i) {
				this.cartGoodList[i].checked = !this.cartGoodList[i].checked
				this.commitCurrentCartInfo(item.goodsid, item.choiceid, item.price, item.goodsnum, item.checked)
				// 只要有一个商品选中状态为false  flag返回为true  将全选按钮状态修改为false
				const flag = this.cartGoodList.some(item => item.checked === false)
				this.cartBottomComputedObj.checkAllState = !flag
				this.getCheckGoodsInfo()
			},
			// 删除选中按钮被点击时触发
			async delChosen() {
				const chosenGoodsId = this.checkedGoodsList.map(item => item.goodsid)
				const { data: res } = await uni.$http.delete('/cart/del', { uid: uni.getStorageSync('uid'), id: chosenGoodsId.join(',') })
				if(res.meta.status !== 200) return uni.showToast({
					title: res.meta.message,
					icon: 'error',
					duration: 1500
				})
				uni.showToast({
					title: res.meta.message,
					icon: 'success',
					duration: 1000
				})
				// 删除商品后刷新用户界面
				this.getUserCartInfo()
			},
		}
	}
</script>

<style>
	page {
		height: 100%;
		background-color: #f2f2f2;
	}
	
	.cart-container {
		height: 100%;
	}
	
	.bottom-compute-area {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}
	
	.van-cell__title {
		font-size: 12px;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	
	.attrchoice-area {
		height: 100rpx;
		line-height: 100rpx;
		font-size: 14px;
	}
	
	.van-rate {
		margin-left: 5rpx;
		height: 38rpx;
	}
	
	.van-rate__item {
		float: left;
	}
	
	.popup-top-area {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.popup-top-area image {
		width: 200rpx;
		height: 200rpx;
	}
	
	.popup-top-area > view {
		flex: 1;
	}
	
	.goods-name {
		margin: 10rpx 0;
	}
	
	.goods-price {
		font-size: 14px;
		color: red;
		padding: 0 10rpx;
	}
	
	.del-chosen {
		font-size: 10px;
		border-bottom: 1px solid skyblue;
	}
</style>
